<template>
    <div v-loading="loading" class="api-detail-container">
        <!-- 接口头部信息 -->
        <div class="api-header">
            <div class="header-left">
                <div class="title-section">
                    <h1 class="api-title">{{ api?.name || '未命名接口' }}</h1>
                    <button class="edit-btn" @click="emit('edit', props.apiId)"
                        v-permission="'project:manage:api:edit'">
                        <IconEdit />
                        <span>编辑</span>
                    </button>
                </div>
                <div class="request-info">
                    <div class="method-path">
                        <span class="method get">{{ api?.method || '-' }}</span>
                        <span class="path">{{ api?.path || '-' }}</span>
                        <button class="copy-btn" @click="copyPath">
                            <IconCopy /> 复制
                        </button>
                    </div>
                    <div class="api-description">
                        <p>{{ api?.description || '-' }}</p>
                    </div>
                </div>
            </div>
            <div class="header-right">
                <div class="api-meta">
                    <span class="update-time">更新于 {{ formatMinutesTime(api?.updated_time) }}</span>
                    <span class="divider">·</span>
                    <span class="modifier">修改者：{{ api?.updater_nickname || '-' }}</span>
                </div>
            </div>
        </div>

        <!-- 请求头 -->
        <div class="section">
            <h2 class="section-title">请求头</h2>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table compact-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>必填</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in (api?.request_headers || [])">
                                <td>{{ item.name }}</td>
                                <td>{{ item.type }}</td>
                                <td>{{ item.required ? '是' : '否' }}</td>
                                <td>{{ item.description }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 请求参数 -->
        <div class="section">
            <h2 class="section-title">请求参数</h2>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table compact-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>必填</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template v-for="(item, index) in (api?.request_params || [])" :key="item.name">
                                <tr>
                                    <td>
                                        <div class="flex-y-center">
                                            {{ item.name }}
                                            <IconAdd v-if="item.type === 'object' || item.type === 'array'"
                                                class="expand-icon" :class="{ 'expanded': expandedItems[item.name] }"
                                                @click="toggleExpansion(item.name)" />
                                        </div>
                                    </td>
                                    <td>{{ item.type }}</td>
                                    <td>{{ item.required ? '是' : '否' }}</td>
                                    <td>{{ item.description }}</td>
                                </tr>
                                <!-- 递归渲染子属性 -->
                                <template
                                    v-if="(item.type === 'object' || item.type === 'array') && expandedItems[item.name]">
                                    <RecursiveParamRow :fields="item.fields" :level="1" :show-required="true"
                                        :expanded-items="expandedItems" :parent-key="item.name"
                                        @toggle-expansion="toggleExpansion" />
                                </template>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 返回参数 -->
        <div class="section">
            <h2 class="section-title">返回参数</h2>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template v-for="(item, index) in (api?.response_params || [])" :key="item.name">
                                <tr>
                                    <td>
                                        <div class="flex-y-center">
                                            {{ item.name }}
                                            <IconAdd v-if="item.type === 'object' || item.type === 'array'"
                                                class="expand-icon" :class="{ 'expanded': expandedItems[item.name] }"
                                                @click="toggleExpansion(item.name)" />
                                        </div>
                                    </td>
                                    <td>{{ item.type }}</td>
                                    <td>{{ item.description }}</td>
                                </tr>
                                <!-- 递归渲染子属性 -->
                                <template
                                    v-if="(item.type === 'object' || item.type === 'array') && expandedItems[item.name]">
                                    <RecursiveParamRow :fields="item.fields" :level="1" :show-required="false"
                                        :expanded-items="expandedItems" :parent-key="item.name"
                                        @toggle-expansion="toggleExpansion" />
                                </template>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 请求示例和响应示例 -->
        <div class="examples-section">
            <div class="example-column">
                <h2 class="section-title">请求示例</h2>
                <div class="code-block">
                    <div class="code-header">
                        <span>cURL</span>
                        <button class="copy-btn small" @click="copyRequestExample">
                            <IconCopy />
                        </button>
                    </div>
                    <pre class="code-content">{{ safeJsonParse(api?.request_example, '-') }}</pre>
                </div>
            </div>

            <div class="example-column">
                <h2 class="section-title">响应示例</h2>
                <div class="code-block">
                    <div class="code-header">
                        <span>JSON</span>
                        <button class="copy-btn small" @click="copyResponseExample">
                            <IconCopy />
                        </button>
                    </div>
                    <pre class="code-content">{{ safeJsonParse(api?.response_example, '-') }}</pre>
                </div>
            </div>
        </div>

        <!-- 创建信息 -->
        <div class="section">
            <h2 class="section-title">创建信息</h2>
            <div class="section-content">
                <div class="create-info">
                    <div class="info-item">
                        <span class="label">创建时间：</span>
                        <span class="value">{{ formatMinutesTime(api?.created_time || '') }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">创建人：</span>
                        <span class="value">{{ api?.creator_nickname }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { getApiDetail } from '@/common/apis/project/index.ts';
import { formatMinutesTime } from '@/common/utils/datetime.ts';
import RecursiveParamRow from './RecursiveParamRow.vue';
import { ApiDetail } from '@/common/apis/project/type';
import { safeJsonParse, safeCopyToClipboard } from '../utils/index.ts';

const props = defineProps({
    apiId: {
        type: [String, Number]
    }
});

const api = ref<ApiDetail>({
    name: '',
    method: '',
    path: '',
    description: '',
    updated_time: '',
    updater_nickname: '',
    request_headers: [],
    request_params: [],
    response_params: []
});

// 递归展开状态管理
const expandedItems = ref<Record<string, boolean>>({});
const emit = defineEmits(['edit']);
const loading = ref(false);

// 切换展开状态
const toggleExpansion = (itemKey: string) => {
    expandedItems.value[itemKey] = !expandedItems.value[itemKey];
};

// 复制路径
const copyPath = () => {
    const path = api.value?.path || 'http://api.example.com/v1/users/{id}';
    safeCopyToClipboard(path, '路径已复制到剪贴板');
};

// 复制请求示例
const copyRequestExample = () => {
    const requestExample = api.value?.request_example || `{
     "id": 20
}`;
    safeCopyToClipboard(requestExample, '请求示例已复制到剪贴板');
};

// 复制响应示例
const copyResponseExample = () => {
    const responseExample = api.value?.response_example || `{
  "code": 200,
  "message": "success",
  "data": {
    "id": 123,
    "username": "john_doe",
    "email": "john@example.com",
    "created_at": "2024-01-01T00:00:00Z"
  }
}`;
    safeCopyToClipboard(responseExample, '响应示例已复制到剪贴板');
};

// 确保组件初始化时发送请求
onMounted(async () => {
    loading.value = true;
    if (props.apiId) {
        try {
            const response = await getApiDetail({ id: Number(props.apiId) }) as any;
            api.value = response.data as ApiDetail;
        } catch (error) {
            console.error('获取API详情失败:', error);
        } finally {
            loading.value = false;
        }
    }
});
</script>

<style scoped lang="less">
.api-detail-container {
    width: 100%;
    height: 100vh;
    padding: 24px;
    background: var(--bg-primary);
    overflow-y: auto;
    position: relative;
    box-sizing: border-box;
}

// 确保父容器也有滚动
:deep(body),
:deep(html) {
    height: 100%;
    overflow-y: auto;
    background: var(--bg-tertiary);
}

.api-header {
    margin-bottom: 20px;
    padding: 20px;
    background: var(--card-bg);
    border-radius: 8px;
    box-shadow: var(--shadow-light);
    border: 1px solid var(--border-light);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
}

.header-left {
    flex: 1;

    .title-section {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;

        .api-title {
            font-size: 20px;
            font-weight: 700;
            color: var(--primary-color);
            margin: 0;
            letter-spacing: -0.5px;
        }

        .edit-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 6px;
            background: var(--primary-color);
            border: 1px solid var(--border-light);
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            color: white;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);

            &:hover {
                background: var(--primary-color);
                border-color: var(--primary-color);
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            &:active {
                transform: translateY(0);
            }

            span {
                font-size: 12px;
            }
        }
    }

    .request-info {
        .method-path {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;

            .method {
                padding: 4px 8px;
                border-radius: 4px;
                font-weight: 700;
                font-size: 11px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

                &.get {
                    background: var(--api-get-bg);
                    color: var(--api-get-color);
                }
            }

            .path {
                flex: 1;
                font-family: 'JetBrains Mono', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                font-size: 12px;
                color: var(--text-primary);
                font-weight: 500;
            }

            .copy-btn {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 4px 8px;
                background: var(--primary-color);
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 11px;
                font-weight: 600;
                color: white;
                transition: all 0.3s ease;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

                &:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
                    background: var(--primary-light);
                }

                &:active {
                    transform: translateY(0);
                }

                svg {
                    width: 12px;
                    height: 12px;
                }
            }
        }

        .api-description {
            p {
                color: var(--text-secondary);
                font-size: 13px;
                line-height: 1.5;
                margin: 0;
            }
        }
    }
}

.header-right {
    .api-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        color: var(--text-secondary);
        font-size: 12px;
        font-weight: 500;
        white-space: nowrap;

        .divider {
            color: var(--text-tertiary);
            font-weight: 300;
        }
    }
}

// 移除旧的 request-section 样式，因为已经合并到 header 中

.section {
    margin-bottom: 16px;
    padding: 16px;
    background: var(--card-bg);
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--border-light);
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    }

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--primary-color);
        margin: 0 0 12px 0;
        padding-bottom: 6px;
        border-bottom: 1px solid var(--border-color);
        position: relative;

        &::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 40px;
            height: 1px;
            background: var(--primary-color);
            border-radius: 1px;
        }
    }

    .section-content {
        color: var(--text-primary);
        line-height: 1.5;
        font-size: 13px;
    }
}

.table-container {
    overflow-x: auto;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    width: 100%;
}

.api-table {
    width: 100%;
    border-collapse: collapse;
    border: none;
    border-radius: 6px;
    overflow: hidden;
    background: var(--card-bg);
    table-layout: fixed;

    th,
    td {
        padding: 10px 12px;
        text-align: left;
        border: 1px solid var(--border-light);
        word-wrap: break-word;
        overflow-wrap: break-word;
    }

    // 三列表格（返回参数）
    th:nth-child(1),
    td:nth-child(1) {
        width: 30%;
    }

    th:nth-child(2),
    td:nth-child(2) {
        width: 15%;
    }

    th:nth-child(3),
    td:nth-child(3) {
        width: 55%;
    }

    // 四列表格（请求头和请求参数）
    &.compact-table {

        th:nth-child(1),
        td:nth-child(1) {
            width: 25%;
        }

        th:nth-child(2),
        td:nth-child(2) {
            width: 15%;
        }

        th:nth-child(3),
        td:nth-child(3) {
            width: 15%;
        }

        th:nth-child(4),
        td:nth-child(4) {
            width: 45%;
        }
    }

    th {
        background: var(--table-header-bg);
        font-weight: 600;
        color: var(--text-primary);
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    td {
        color: var(--text-secondary);
        font-size: 12px;
        font-weight: 500;
    }

    tr:last-child td {
        border-bottom: none;
    }

    tr:hover {
        background: rgba(107, 114, 128, 0.1) !important;
        transition: background-color 0.2s ease;
    }

    // 展开图标样式
    .expand-icon {
        cursor: pointer;
        transition: all 0.3s ease;
        margin-left: 8px;
        font-size: 13px;
        fill: var(--text-secondary);

        &:hover {
            fill: var(--primary-color);
            transform: scale(1.1);
        }

        &.expanded {
            transform: rotate(45deg);
            fill: var(--primary-color);
        }
    }
}

.examples-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;

    .example-column {
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--primary-color);
            margin: 0 0 12px 0;
            padding-bottom: 6px;
            border-bottom: 1px solid var(--border-color);
            position: relative;

            &::after {
                content: '';
                position: absolute;
                bottom: -1px;
                left: 0;
                width: 40px;
                height: 1px;
                background: var(--primary-color);
                border-radius: 1px;
            }
        }
    }
}

.code-block {
    border: none;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    background: var(--card-bg);
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    }

    .code-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: var(--code-header-bg);
        border-bottom: 1px solid var(--border-light);
        font-size: 11px;
        font-weight: 600;
        color: var(--text-primary);
        text-transform: uppercase;
        letter-spacing: 0.5px;

        .copy-btn.small {
            padding: 4px 8px;
            font-size: 11px;
            background: var(--primary-color);
            border: none;
            border-radius: 4px;
            color: white;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

            &:hover {
                background: var(--primary-light);
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
            }

            svg {
                width: 12px;
                height: 12px;
            }
        }
    }

    .code-content {
        margin: 0;
        padding: 12px;
        background: var(--code-bg);
        font-family: 'JetBrains Mono', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 12px;
        line-height: 1.4;
        color: var(--text-primary);
        overflow-x: auto;
        position: relative;
        border: 1px solid var(--border-light);

        code {
            background: none;
            padding: 0;
            color: inherit;
        }

        // 语法高亮
        .string {
            color: var(--success-color);
        }

        .number {
            color: var(--warning-color);
        }

        .boolean {
            color: var(--error-color);
        }

        .null {
            color: var(--info-color);
        }

        .key {
            color: var(--primary-color);
        }
    }
}

.create-info {
    display: flex;
    gap: 16px;
    padding: 12px;
    background: var(--bg-tertiary);
    border-radius: 6px;
    border: 1px solid var(--border-light);

    .info-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background: var(--card-bg);
        border-radius: 4px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
        }

        .label {
            font-weight: 600;
            color: var(--text-secondary);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .value {
            color: var(--text-primary);
            font-weight: 600;
            font-size: 13px;
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .api-detail-container {
        padding: 16px;
    }

    .api-header,
    .section {
        padding: 20px;
    }

    .examples-section {
        grid-template-columns: 1fr;
        gap: 20px;
    }

    .method-path {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        padding: 20px;

        .path {
            word-break: break-all;
        }
    }

    .create-info {
        flex-direction: column;
        gap: 16px;
        padding: 20px;

        .info-item {
            justify-content: center;
        }
    }

    .api-table {

        th,
        td {
            padding: 12px 16px;
            font-size: 13px;
        }
    }

    .code-block {
        .code-content {
            padding: 16px;
            font-size: 13px;
        }
    }
}

// 添加一些动画效果
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.api-header,
.request-section,
.section,
.examples-section {
    animation: fadeInUp 0.6s ease-out;
}

.section:nth-child(3) {
    animation-delay: 0.1s;
}

.section:nth-child(4) {
    animation-delay: 0.2s;
}

.section:nth-child(5) {
    animation-delay: 0.3s;
}

.section:nth-child(6) {
    animation-delay: 0.4s;
}

.examples-section {
    animation-delay: 0.5s;
}

.section:nth-child(8) {
    animation-delay: 0.6s;
}

.action-section {
    margin-bottom: 40px;
    animation: fadeInUp 0.8s ease-out 0.6s both;
}

.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 12px;
    padding: 16px 32px;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    i {
        font-size: 20px;
    }

    &:hover {
        background: var(--primary-light);
        transform: translateY(-3px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    }

    &:active {
        transform: translateY(-1px);
    }
}

// 脉冲动画
@keyframes pulse {

    0%,
    100% {
        transform: scale(1);
        opacity: 0.8;
    }

    50% {
        transform: scale(1.1);
        opacity: 1;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .default-page {
        padding: 24px;
    }

    .default-title {
        font-size: 28px;
    }

    .default-description {
        font-size: 16px;
    }

    .action-btn {
        padding: 14px 28px;
        font-size: 15px;
    }
}

@media (max-width: 480px) {
    .default-icon i {
        font-size: 60px;
    }

    .default-title {
        font-size: 24px;
    }

    .default-description {
        font-size: 14px;
    }

    .action-btn {
        padding: 12px 24px;
        font-size: 14px;
    }
}
</style>